package top.roud.sso.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import top.roud.sso.service.TokenService;
import top.roud.sso.utils.CacheUtil;
import top.roud.sso.utils.JwtUtil;
import top.roud.sso.utils.RandomCodeUtil;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author roud
 * @version 1.0.0
 * @describe
 * @date 2025-01-20 20:10
 */
@Service
public class TokenServiceImpl implements TokenService {

    @Autowired
    private CacheUtil cacheUtil;

    @Autowired
    private JwtUtil jwtUtil;

    @Value("${roud-sso.expire}")
    private int EXPIRE_TIME;

    private final String tokenNJwtsign = "roud.sso.token.n.jwtsign.";
    private final String keyNToken = "roud.sso.key.n.token.";

    @Override
    public String getToken(String key, Map<String, Object> map) {
        loseKey(key);
        String randCode = RandomCodeUtil.getRandomCode(6);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String token = randCode+"_"+uuid;
        String sign = jwtUtil.sign(key, map);
        cacheUtil.putToCache(tokenNJwtsign + token, sign, EXPIRE_TIME, TimeUnit.DAYS);
        cacheUtil.putToCache(keyNToken + key, token, EXPIRE_TIME, TimeUnit.DAYS);
        return token;
    }

    @Override
    public boolean loseKey(String key) {
        try{
            String token = cacheUtil.getByCache(keyNToken + key);
            if(StringUtils.isNotBlank(token)){
                cacheUtil.delCache(tokenNJwtsign + token);
            }
            cacheUtil.delCache(keyNToken + key);
        }catch (Exception e){
            return false;
        }
        return true;
    }

    @Override
    public boolean loseToken(String token) {
        try{
            cacheUtil.delCache(tokenNJwtsign + token);
        }catch (Exception e){
            return false;
        }
        return true;
    }

    @Override
    public boolean checkToken(String token) {
        String sign = cacheUtil.getByCache(tokenNJwtsign + token);
        if(StringUtils.isBlank(sign)){
            return false;
        }
        return jwtUtil.checkSign(sign);
    }

    @Override
    public Map<String, Object> getInfo(String token) {
        String sign = cacheUtil.getByCache(tokenNJwtsign + token);
        if(StringUtils.isBlank(sign)){
            return null;
        }
        return jwtUtil.getInfo(sign);
    }
}
